package com.ruoyi.project.upload.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.baidu.aip.ocr.AipOcr;
import com.ruoyi.common.exception.file.FileUploadException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.upload.domain.ExtractImage;
import net.coobird.thumbnailator.Thumbnails;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.upload.mapper.UploadImagesMapper;
import com.ruoyi.project.upload.domain.UploadImages;
import com.ruoyi.project.upload.service.IUploadImagesService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传图片信息Service业务层处理
 *
 * @author fanzhihao
 * @date 2023-03-23
 */

@Service
public class UploadImagesServiceImpl implements IUploadImagesService {

    private static final String IMAGE_SUFFIX_J = "jpg";
    private static final String IMAGE_SUFFIX_P = "png";
    private static final Long USER_ID= 1L;

    @Autowired
    private UploadImagesMapper uploadImagesMapper;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private AipOcr client;

    /**
     * 查询上传图片信息
     *
     * @param id 上传图片信息主键
     * @return 上传图片信息
     */
    @Override
    public UploadImages selectUploadImagesById(Long id) {
        return uploadImagesMapper.selectUploadImagesById(id);
    }

    /**
     * 查询上传图片信息列表
     *
     * @param uploadImages 上传图片信息
     * @return 上传图片信息
     */
    @Override
    public List<UploadImages> selectUploadImagesList(UploadImages uploadImages) {

        return uploadImagesMapper.selectUploadImagesList(uploadImages);
    }

    /**
     * 新增上传图片信息
     *
     * @param uploadImages 上传图片信息
     * @return 结果
     */
    @Override
    public int insertUploadImages(UploadImages uploadImages) {
        return uploadImagesMapper.insertUploadImages(uploadImages);
    }

    /**
     * 修改上传图片信息
     *
     * @param uploadImages 上传图片信息
     * @return 结果
     */
    @Override
    public int updateUploadImages(UploadImages uploadImages) {
        return uploadImagesMapper.updateUploadImages(uploadImages);
    }

    /**
     * 批量删除上传图片信息
     *
     * @param ids 需要删除的上传图片信息主键
     * @return 结果
     */
    @Override
    public int deleteUploadImagesByIds(Long[] ids) {
        return uploadImagesMapper.deleteUploadImagesByIds(ids);
    }

    /**
     * 删除上传图片信息信息
     *
     * @param id 上传图片信息主键
     * @return 结果
     */
    @Override
    public int deleteUploadImagesById(Long id) {
        return uploadImagesMapper.deleteUploadImagesById(id);
    }

    /**
     * 图片上传
     *
     * @param files
     * @return
     */
    @Override
    public int uploadImages(List<MultipartFile> files) {

        Date date = new Date();
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        for (MultipartFile file : files) {

            // 上传并返回新文件名称
            String fileName = null;
            ExtractImage extractImage = null;
            try {
                //fileName = FileUploadUtils.upload(filePath, file);
                extractImage = FileUploadUtils.upload_yasuo2(filePath, file, client);
                fileName = extractImage.getPathName();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //String url = serverConfig.getUrl() + fileName;
            //String path = path(url);
            //File newFile = new File(path);
            //ImageZipUtil.zipWidthHeightImageFile(f, newFile, 510, 1092, 0.7f);

            //获取用户的信息
            SysUser user = SecurityUtils.getLoginUser().getUser();
            UploadImages uploadImages = new UploadImages();
            uploadImages.setUserId(user.getUserId());
            //读取图片时间
            uploadImages.setUrl(fileName);
            uploadImages.setBatch(DateUtils.dateTimeNow("yyyy-MM-dd"));
            uploadImages.setCreatedTime(date);
            uploadImages.setTime(extractImage.getTime());
            uploadImages.setMoney(extractImage.getMoney());

            int i = uploadImagesMapper.insertUploadImages(uploadImages);
            if (i != 1) {
                throw new RuntimeException();
            }
        }

        return 1;
    }

    /**
     * 本地图片地址url
     *
     * @param url http式url
     * @return 本地路径
     */
    private String path(String url) {
        String s = url.substring(36);
        String filePath = RuoYiConfig.getUploadPath();
        //完整路径
        String completePath = filePath + s;
        String replace = completePath.replace("/", "\\");
        return replace;
    }

    /**
     * 读取图片内容
     *
     * @param
     */
    private ExtractImage readImage(File file) {
        try {
            //创建Tesseract对象
            ITesseract tesseract = new Tesseract();
            //设置字体库路径
            tesseract.setDatapath("src/main/resources/tessdata");
            //中文识别
            tesseract.setLanguage("chi_sim");
            //执行ocr识别
            String result = tesseract.doOCR(file);
            //使用正则替换：\r回车 \n换行, \s任何空白字符
            result = result.replaceAll("\\r|\\n", "-").replaceAll(" ", "");
            ExtractImage extractImage = new ExtractImage();
            extractImage.setTime(time(result));
            extractImage.setMoney(money(result));
            return extractImage;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 提取日期
     *
     * @param text
     */
    public Date time(String text) {
        String pattern = "([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]|[0-9][1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(text);
        Date newTime = null;
        while (m.find()) {
            String result = m.group(0);
            StringBuffer sb = new StringBuffer(result);
            sb.insert(10, " ");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                newTime = format.parse(String.valueOf(sb));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return newTime;
    }

    /**
     * 提取金额
     *
     * @param text
     * @return
     */
    private BigDecimal money(String text) {
        String pattern = "(\\d+\\.\\d+)";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(text);
        while (m.find()) {
            String group = m.group(0);
            BigDecimal money = new BigDecimal(group);
            return money;
        }
        return null;
    }



}
